package com.xx.springsecuritydemo.main.filter;

import com.xx.springsecuritydemo.main.exception.KaptchaNotMatchException;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 前后端不分离处理验证码
 */
public class KaptchaFilter extends UsernamePasswordAuthenticationFilter {
    // 默认值
    public static final String KAPTCHA_KEY = "kaptcha";

    private String kaptcha = KAPTCHA_KEY;

    public String getKaptcha() {
        return kaptcha;
    }
    public void setKaptcha(String kaptcha) {
        this.kaptcha = kaptcha;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        // 1.获取请求数据
        //⽤来获取数据中验证码
        String kaptcha = request.getParameter(getKaptcha());
        // 2.获取 session 中验证码
        String sessionVerifyCode = (String) request.getSession().getAttribute("kaptcha");
        if (!ObjectUtils.isEmpty(kaptcha) &&
                !ObjectUtils.isEmpty(sessionVerifyCode) &&
                kaptcha.equalsIgnoreCase(sessionVerifyCode)) {
            return super.attemptAuthentication(request, response);
        }

        throw new KaptchaNotMatchException("验证码不匹配!");
    }
}
